<template>
  <div class="analysis-page">
    <div class="analysis-header">
      <h2 class="main-title">配置仿真环境参数</h2>
      <div class="sub-title">请拖拽或点击选择所需参数</div>
    </div>
    <div class="analysis-content">
      <!-- 左侧面板 -->
      <div class="sidebar">
        <el-collapse v-model="activeNames">
          <el-collapse-item v-for="(items, parameter) in parameterData" :key="parameter" :name="parameter">
            <template #title>
              <span class="category-title">
                <i class="iconfont" :class="categoryIcons[parameter]" style="font-size:18px;margin-right:8px;"></i>
                {{ MappingName(parameter) }}
              </span>
            </template>
            <div class="category-items">
              <div
                v-for="item in items"
                :key="item.id"
                class="drag-item"
                draggable="true"
                :data-type="parameter"
                :data-value="JSON.stringify(item)"
                @dragstart="handleDragStart"
                @click="handleClick(item, parameter)"
              >
                <div v-if="item.icon && item.icon.startsWith('<svg')" v-html="item.icon" class="icon-container"></div>
                <img v-else-if="item.icon && (item.icon.endsWith('.png') || item.icon.endsWith('.jpg') || item.icon.endsWith('.jpeg') || item.icon.endsWith('.svg'))"
                     :src="item.icon" :alt="item.parameter_name" class="icon-image" />
                <div v-else class="default-icon">📊</div>
                <span>{{ item.name }}</span>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <!-- 中间展示区域 -->
      <div class="main-area">
        <div class="drop-container">
          <div v-for="slot in dropSlots" :key="slot.type" class="drop-slot" :class="{ 'has-item': slot.hasItem }"
            :data-accept="slot.type" :data-value="slot.name" @dragover="handleDragOver" @drop="handleDrop">
            <div v-if="slot.hasItem" class="dropped-item">
              <div v-if="slot.icon && slot.icon.startsWith('<svg')" v-html="slot.icon" class="icon-container"></div>
              <img
                v-else-if="slot.icon && (slot.icon.endsWith('.png') || slot.icon.endsWith('.jpg') || slot.icon.endsWith('.jpeg') || slot.icon.endsWith('.svg'))"
                :src="slot.icon" :alt="slot.name" class="icon-image" />
              <div v-else class="default-icon"></div>
              <span>{{ slot.name }}</span>
            </div>
            <div v-else class="drop-placeholder">
              <!-- <div class="placeholder-icon"></div> -->
              <i
                class="iconfont"
                :class="categoryIcons[slot.type]"
                style="font-size:22px;vertical-align:middle;"
              ></i>
              <span>{{ slot.label }}</span>
            </div>
          </div>
        </div>

        <!-- 按钮区域 -->
        <div class="button-area">
          <button class="clear-button" @click="clearAllSlots">清空所有</button>
          <button class="action-button" @click="handleAnalysis">
            创建环境
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref } from "vue";
import { getAllParameters, getAllCategory, addSimulation } from '../api/system/parameter';
import { ElMessage, ElMessageBox } from 'element-plus';

onMounted(() => {
  getAllCategory().then(res => {
    const categoryList = res.data.data
    let mappingList = {}
    let items = [] // 所有参数
    for (let i of categoryList["categorys"]) {
      mappingList[i.category_name] = i.category_id
    }
    items = categoryList["items"]
    parameterData.weather = items.filter(item => item.category_id === mappingList["光照"])
    parameterData.temperature = items.filter(item => item.category_id === mappingList["温度"])
    parameterData.wind = items.filter(item => item.category_id === mappingList["风力"])
    parameterData.humidity = items.filter(item => item.category_id === mappingList["湿度"])
    parameterData.load = items.filter(item => item.category_id === mappingList["负荷"])
    parameterData.windPrice = items.filter(item => item.category_id === mappingList["风电"])
    parameterData.lightPrice = items.filter(item => item.category_id === mappingList["光电"])
    parameterData.gridPrice = items.filter(item => item.category_id === mappingList["国网"])
    parameterData.batteryPrice = items.filter(item => item.category_id === mappingList["电池"])
    console.log(parameterData)
  })

  // 默认全部展开
  activeNames.value = Object.keys(parameterData);
  // getAllParameters().then(res => {
  //   let cacheList = res.data.data
  //   const weatherList = cacheList.filter(item => item.category_id === 4)
  //   console.log(weatherList)
  //   const temperatureList = cacheList.filter(item => item.category_id === 1)
  //   const windList = cacheList.filter(item => item.category_id === 3)
  //   const humidityList = cacheList.filter(item => item.category_id === 2)
  //   const loadList = cacheList.filter(item => item.category_id === 5)
  //   const windPriceList = cacheList.filter(item => item.category_id === 6)
  //   const lightPriceList = cacheList.filter(item => item.category_id === 7)
  //   const gridPriceList = cacheList.filter(item => item.category_id === 8)
  //   const batteryPriceList = cacheList.filter(item => item.category_id === 9)
  //   parameterData.weather = weatherList
  //   parameterData.temperature = temperatureList
  //   parameterData.wind = windList
  //   parameterData.humidity = humidityList
  //   parameterData.load = loadList
  //   parameterData.windPrice = windPriceList
  //   parameterData.lightPrice = lightPriceList
  //   parameterData.gridPrice = gridPriceList
  //   parameterData.batteryPrice = batteryPriceList
  // })
})

const categoryIcons = {
  weather: 'icon-tianqicanshu',      // 天气
  temperature: 'icon-wendu',   // 温度
  wind: 'icon-fenglijiance',         // 风力
  humidity: 'icon-shidu-01',      // 湿度
  load: 'icon-yongdianfuhe',           // 负荷
  windPrice: 'icon-_shouyexianjinTA',  // 风电价
  lightPrice: 'icon-creativity',// 光电价
  gridPrice: 'icon-guowangdianjia',   // 国网电价
  batteryPrice: 'icon-dianchicanshu' // 电池
};

let selectedParams = []
// 参数数据
const parameterData = reactive({
  weather: [],
  temperature: [],
  wind: [],
  humidity: [],
  load: [],
  windPrice: [],
  lightPrice: [],
  gridPrice: [],
  batteryPrice: [],
})

// 放置区域
const dropSlots = reactive([
  { type: 'weather', label: '天气参数', hasItem: false, name: '', icon: '', bg: '', original_id: '' },
  { type: 'temperature', label: '温度参数', hasItem: false, name: '', icon: '', bg: '', original_id: '' },
  { type: 'wind', label: '风力参数', hasItem: false, name: '', icon: '', bg: '', original_id: '' },
  { type: 'humidity', label: '湿度参数', hasItem: false, name: '', icon: '', bg: '', original_id: '' },
  { type: 'load', label: '负荷参数', hasItem: false, name: '', icon: '', bg: '', original_id: '' },
  { type: 'windPrice', label: '风电价', hasItem: false, name: '', icon: '', bg: '', original_id: '' },
  { type: 'lightPrice', label: '光电价', hasItem: false, name: '', icon: '', bg: '', original_id: '' },
  { type: 'gridPrice', label: '国网电价', hasItem: false, name: '', icon: '', bg: '', original_id: '' },
  { type: 'batteryPrice', label: '电池参数', hasItem: false, name: '', icon: '', bg: '', original_id: '' },
])

const activeNames = ref([]);



function MappingName(type) {
  if (type === 'weather') {
    return '天气参数'
  } else if (type === 'temperature') {
    return '温度参数'
  } else if (type === 'wind') {
    return '风力参数'
  } else if (type === 'humidity') {
    return '湿度参数'
  } else if (type === 'load') {
    return '负荷参数'
  } else if (type === 'windPrice') {
    return '风电价'
  } else if (type === 'lightPrice') {
    return '光电价'
  } else if (type === 'gridPrice') {
    return '国网电价'
  } else if (type === 'batteryPrice') {
    return '电池参数'
  }
}

function handleDragStart(e) {
  const type = e.target.dataset.type
  const value = JSON.parse(e.target.dataset.value)
  e.dataTransfer.setData('text/plain', JSON.stringify({ type, value }))
  e.dataTransfer.effectAllowed = 'move'
}

function handleDragOver(e) {
  e.preventDefault()
  e.dataTransfer.dropEffect = 'move'
}

function handleDrop(e) {
  e.preventDefault()
  const dataStr = e.dataTransfer.getData('text/plain')
  const { type, value } = JSON.parse(dataStr)
  const acceptType = e.target.closest('.drop-slot').dataset.accept
  if (type !== acceptType) return
  const param = parameterData[type].find(i => i.value === value)
  const iconUrl = param ? param.icon : ''
  const bgUrl = param ? param.bg : ''
  const slotIndex = dropSlots.findIndex(slot => slot.type === acceptType)
  if (slotIndex !== -1) {
    dropSlots[slotIndex].hasItem = true
    dropSlots[slotIndex].name = value.name
    dropSlots[slotIndex].icon = value.icon
    dropSlots[slotIndex].bg = value.background
  }
}

function handleClick(item, type) {
  const slotIndex = dropSlots.findIndex(slot => slot.type === type)
  if (slotIndex !== -1) {
    dropSlots[slotIndex].hasItem = true
    dropSlots[slotIndex].name = item.name
    dropSlots[slotIndex].icon = item.icon
    dropSlots[slotIndex].bg = item.background
    dropSlots[slotIndex].original_id = item.original_id
    // 不要覆盖 type
  }
}

async function handleAnalysis() {
  const allSelected = dropSlots.every(slot => slot.hasItem)
  if (!allSelected) {
    ElMessage.warning('请先选择所有参数')
    return
  }

  // 弹窗输入环境名
  try {
    const { value: envName } = await ElMessageBox.prompt('请输入环境名称', '环境名称', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /\S+/,
      inputErrorMessage: '环境名称不能为空',
      inputValue: '环境名称'+new Date().getTime()
    });

    // 继续后续逻辑
    const selectedParams = dropSlots.map(slot => ({
      type: slot.type,
      original_id: slot.original_id
    }))
    let data = {
      granularity: 24,
      period: 1,
      period_unit: 'day',
      battery: null,
      initial_capacity: 0,
      price_ids: null,
      parameter_ids: null,
      name: envName // 新增环境名
    }
    let parameter_ids = []
    let price_ids = []
    for (let i = 0; i < 5; i++) {
      parameter_ids.push(selectedParams[i].original_id)
    }
    for (let i = 5; i < 8; i++) {
      price_ids.push(selectedParams[i].original_id)
    }
    data.parameter_ids = parameter_ids
    data.price_ids = price_ids
    data.battery = selectedParams[8].original_id
    addSimulation(JSON.stringify(data)).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('创建成功')
      } else {
        ElMessage.error(res.data.message || '创建失败')
      }
    })
  } catch (e) {
    // 用户取消，无需处理
  }
}

function clearAllSlots() {
  for (const slot of dropSlots) {
    slot.hasItem = false
    slot.name = ''
    slot.icon = ''
    slot.bg = ''
    slot.original_id = ''
  }
}
</script>

<style scoped>
.analysis-page {
  width: 100%;
  height: 85vh;
  display: flex;
  flex-direction: column;
  /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
}


.analysis-header p {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
  font-weight: 500;
}

.analysis-content {
  flex: 1;
  display: flex;
  gap: 24px;
  padding: 20px;
  overflow: hidden;
}

.sidebar {
  width: 400px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.10);
  border: 1px solid #e3eaf1;
  padding: 18px 16px;
  display: flex;
  flex-direction: column;
  gap: 18px;
  overflow-y: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.sidebar::-webkit-scrollbar {
  display: none;
}

/* Element Plus 折叠面板整体 */
:deep(.el-collapse) {
  background: transparent;
  border: none;
  box-shadow: none;
  padding: 0;
}

/* 折叠面板标题 */
:deep(.el-collapse-item__header) {
  font-size: 16px;
  font-weight: 700;
  color: #222; /* 改为黑色 */
  background: #f8fafc;
  border-radius: 8px 8px 0 0;
  border-bottom: 1.5px solid #6985a0;  /* 新增底部边框 */
  margin-bottom: 0;
  padding: 10px 0;
  transition: background 0.2s;
  display: flex;
  align-items: center;
  justify-content: center; /* 居中 */
}
:deep(.el-collapse-item__header:hover) {
  background: #e3f2fd;
}

/* 折叠箭头 */
:deep(.el-collapse-item__arrow) {
  color: #a3a6a8;
  font-size: 20px;
  margin-right: 8px;
}

:deep(.el-collapse-item__title) {
  text-align: center;
}

/* 折叠内容区域 */
:deep(.el-collapse-item__wrap) {
  background: #fff;
  border-radius: 0 0 12px 12px;
  padding-bottom: 8px;
}
:deep(.el-collapse-item__content) {
  padding: 0 18px 8px 18px;
}

/* 类别标题（可选，增强可读性） */
.category-title {
  font-size: 16px;
  font-weight: 700;
  color: #222; /* 改为黑色 */
  width: 100%;
  text-align: center; /* 居中 */
}

/* 参数选项区 */
.category-items {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-top: 8px;
}

/* 拖拽项样式 */
.drag-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px 4px;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  cursor: pointer;
  border-radius: 10px;
  border: 2px solid transparent;
  transition: all 0.3s;
  user-select: none;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.drag-item:hover,
.drag-item.selected,
.drag-item.border-blue-500 {
  border-color: #1976d2 !important;
  background: linear-gradient(135deg, #e3f2fd, #bbdefb);
  box-shadow: 0 8px 25px rgba(33,150,243,0.15);
}
.drag-item span {
  font-size: 13px;
  font-weight: 500;
  color: #1976d2;
  margin-top: 2px;
}

.drag-item img,
.drag-item .icon-image {
  width: 20px;
  height: 20px;
  object-fit: contain;
  margin-bottom: 3px;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.drag-item .icon-container {
  width: 20px;
  height: 20px;
  margin-bottom: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.drag-item .icon-container svg {
  width: 20px;
  height: 20px;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.drag-item .default-icon {
  width: 20px;
  height: 20px;
  margin-bottom: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.drag-item span {
  font-size: 9px;
  font-weight: 600;
  text-align: center;
  color: #495057;
}

.main-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.drop-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  width: 100%;
  max-width: 500px;
}

.drop-slot {
  aspect-ratio: 1;
  border: 2px solid transparent;
  background: linear-gradient(white, white) padding-box,
    linear-gradient(135deg, #667eea, #764ba2) border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #718096;
  font-size: 14px;
  position: relative;
  text-align: center;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  position: relative;
}

.drop-slot::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 12px;
  z-index: 1;
}

.drop-slot.has-item {
  border-color: #e3f2fd;
  background: linear-gradient(135deg, #eef1f6, #e0e8f7);
  transform: scale(1.02);
}

.drop-slot:hover {
  background: linear-gradient(white, white) padding-box； linear-gradient(135deg, #4299e1, #667eea) border-box;
  transform: translateY(-4px);
}

.drop-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  justify-content: center;
  gap: 8px;
  z-index: 2;
  /* 确保占位符在背景之上 */
}

.placeholder-icon {
  font-size: 32px;
  opacity: 0.6;
}

.drop-placeholder span {
  font-size: 12px;
  font-weight: 600;
  color: #718096;
}

.dropped-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  font-weight: 700;
  z-index: 2;
  /* 确保放置的物品在背景之上 */
}

.dropped-item img,
.dropped-item .icon-image {
  width: 32px;
  height: 32px;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
}

.dropped-item .icon-container {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dropped-item .icon-container svg {
  width: 32px;
  height: 32px;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
}

.dropped-item .default-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.dropped-item span {
  font-size: 12px;
  color: #2d3748;
  font-weight: 700;
}

.button-area {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.action-button {
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.action-button:active {
  transform: translateY(0);
}

.clear-button {
  padding: 12px 24px;
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  margin-right: 16px;
  transition: background 0.2s;
  box-shadow: 0 4px 15px rgba(245, 108, 108, 0.2);
}

.clear-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(203, 130, 139, 0.6);
}

.clear-button:active {
  transform: translateY(0);
}

.main-title {
  font-size: 30px;
  font-weight: bold;
  height:50px;
  margin:0;
  color: #000000;
  text-align: center;
  letter-spacing: 2px;
}

.sub-title {
  font-size: 16px;
  color: #666;
  text-align: center;
  margin-bottom: 5px;
  letter-spacing: 1px;
}


/* 响应式设计 */
@media (max-width: 1200px) {
  .drop-container {
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .analysis-header {
    padding: 10px;
  }

  .analysis-header h2 {
    font-size: 24px;
  }

  .analysis-content {
    padding: 16px;
    flex-direction: column;
    gap: 16px;
  }

  .sidebar {
    width: 100%;
    padding: 16px;
    max-height: 300px;
  }

  .category-items {
    grid-template-columns: repeat(4, 1fr);
  }

  .drop-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }

  .drop-slot {
    aspect-ratio: 1;
  }
}

@media (max-width: 480px) {
  .analysis-header {
    padding: 16px;
  }

  .analysis-header h2 {
    font-size: 20px;
  }

  .analysis-content {
    padding: 12px;
  }

  .sidebar {
    padding: 12px;
  }

  .category-items {
    grid-template-columns: repeat(3, 1fr);
    gap: 6px;
  }

  .drag-item {
    padding: 8px 6px;
  }

  .drag-item img {
    width: 20px;
    height: 20px;
  }

  .drop-container {
    grid-template-columns: 1fr;
    gap: 10px;
  }

  .drop-slot {
    aspect-ratio: 2/1;
  }
}
</style>
